<template>
  <el-dialog
    :title="title"
    v-loading="loading"
    v-model="props.params.visible"
    width="1100px"
    append-to-body
    :before-close="cancel"
  >
    <el-form
      :model="addForm"
      ref="addRef"
      :inline="true"
      :rules="addRules"
      label-width="80px"
    >
      <el-form-item label="运费" prop="expressFee">
        <el-input-number
          :min="0"
          v-model="addForm.expressFee"
          placeholder="请输入运费"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="入库时间" prop="warehouseEntryTime">
        <el-date-picker
          style="width: 220px"
          v-model="addForm.warehouseEntryTime"
          type="datetime"
          placeholder="打款时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="回收价格" prop="recyclePrice">
        <el-input-number
          v-model="addForm.recyclePrice"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="商品编码" prop="ref">
        <el-input
          :disabled="isUpdate"
          v-model="addForm.ref"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="商品型号" prop="model">
        <el-input
          :disabled="isUpdate"
          v-model="addForm.model"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="快递单号" prop="expressNo">
        <el-input
          :disabled="isUpdate"
          v-model="addForm.expressNo"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>

      <el-form-item label="品牌" prop="brand">
        <el-select
          v-model="addForm.brand"
          filterable
          reserve-keyword
          clearable
          remote
          :remote-method="getItemBrand"
          @change="brandChange"
          :disabled="isUpdate"
          default-first-option
          placeholder="请选择"
          style="width: 220px"
        >
          <el-option
            v-for="item in item_brand"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品类目" prop="category">
        <el-select
          v-model="addForm.category"
          filterable
          clearable
          :disabled="isUpdate"
          @change="categoryChange"
          placeholder="请选择商品类目"
          style="width: 220px"
        >
          <el-option
            v-for="item in goods_category"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="打款时间" prop="paymentTime">
        <el-date-picker
          :disabled="isUpdate"
          style="width: 220px"
          v-model="addForm.paymentTime"
          type="datetime"
          placeholder="打款时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="打款状态" prop="paymentStatus">
        <el-select
          v-model="addForm.paymentStatus"
          filterable
          clearable
          :disabled="isUpdate"
          @change="paymentStatusChange"
          placeholder="请选择"
          style="width: 220px"
        >
          <el-option
            v-for="item in payment_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回收人" prop="recyclePersonId">
        <el-select
          v-model="addForm.recyclePersonId"
          filterable
          :disabled="isUpdate"
          style="width: 220px"
          remote
          reserve-keyword
          placeholder="请选择回收人"
          :remote-method="getUserOption"
          @change="handleChooseUser"
          :loading="userLoading"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回收客户" prop="recycleCustomer">
        <el-input
          :disabled="isUpdate"
          v-model="addForm.recycleCustomer"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsStatus">
        <el-select
          v-model="addForm.goodsStatus"
          filterable
          clearable
          :disabled="isUpdate"
          placeholder="请选择"
          style="width: 220px"
        >
          <el-option
            v-for="item in goods_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          :disabled="isUpdate"
          v-model="addForm.remark"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="回收编码" prop="recycleCode">
        <el-input
          :disabled="isUpdate"
          v-model="addForm.recycleCode"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>

      <!-- <row>
        <el-form-item label="商品正面" prop="file1">
          <el-upload
            v-model:file-list="fileList"
            ref="upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :limit="1"
            :disabled="true"
            :on-exceed="handleExceed"
            accept=".jpg,.png,.jpeg"
            :auto-upload="false"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品背面" prop="file2">
          <el-upload
            v-model:file-list="fileListBack"
            ref="upload"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :limit="1"
            :disabled="true"
            :on-exceed="handleExceed"
            accept=".jpg,.png,.jpeg"
            :auto-upload="false"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </row> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  addRegister,
  getRegister,
  updateRegister,
} from "@/api/purchase/register";
import { optionSelect } from "@/api/system/skesItem";
import { userOptionSelect } from "@/api/system/user";
import { listData } from "@/api/system/dict/data";

import { computed, watchEffect } from "vue";
const props = defineProps({
  params: Object,
  visible: Boolean,
  options: Array,
});
const emits = defineEmits(["update:visible", "refresh"]);
const { proxy } = getCurrentInstance();
const { payment_status, goods_category, goods_status } = proxy.useDict(
  "payment_status",
  "goods_category",
  "goods_status"
);
const title = computed(() =>
  props.params.type === "add" ? "入库" : "入库修改"
);
const loading = ref(false);
const addForm = ref({
  expressFee: undefined,
  paymentStatus: undefined,
  paymentStatusName: undefined,
  cateGory: undefined,
  cateGoryName: undefined,
  remark: undefined,
  brand: undefined,
  brandName: undefined,
  customerName: undefined,
  recycleTime: undefined,
  paymentTime: undefined,
  warehouseEntryTime: undefined,
  recyclePerson: undefined,
  recyclePrice: undefined,
});
const addRules = ref({
  expressFee: [
    { required: false, message: "运费不能为空", trigger: "blur" },
  ],
  recyclePersonId: [
    { required: true, message: "回收人不能为空", trigger: "blur" },
  ],

  customerName: [
    { required: true, message: "客户姓名不能为空", trigger: "blur" },
  ],
  paymentStatus: [
    { required: true, message: "打款情况不能为空", trigger: "blur" },
  ],
  recyclePerson: [
    { required: true, message: "回收人不能为空", trigger: "blur" },
  ],
  itemId: [{ required: true, message: "商品不能为空", trigger: "blur" }],
  paymentTime: [
    { required: true, message: "打款时间不能为空", trigger: "blur" },
  ],
});
const shortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];
const isUpdate = ref(false);
watchEffect(() => {
  const { visible, type } = props.params;
  if (visible) getDetail();
  isUpdate.value = type === "add" ? true : false;
  addRules.value.expressFee[0].required = type === "add"
});

function categoryChange(val) {
  try {
    const option = goods_category.value.find((i) => i.value === val);
    addForm.value.categoryName = option.label;
  } catch (err) {}
}

function paymentStatusChange(val) {
  try {
    const option = payment_status.value.find((i) => i.value === val);
    addForm.value.paymentStatusName = option.label;
  } catch (err) {}
}
/** 品牌 */
const brandLoading = ref(false);
const item_brand = ref([]);
function brandChange(val) {
  try {
    const option = item_brand.value.find((i) => i.value === val);
    addForm.value.brandName = option.label;
  } catch (error) {}
}
async function getItemBrand(query) {
  if (query) {
    brandLoading.value = true;
    let label = "";
    let val = "";
    if (isNaN(query)) {
      label = query;
    } else {
      val = query;
    }
    const { rows } = await listData({
      pageNum: 1,
      pageSize: 10,
      dictType: "item_brand",
      dictValue: val,
      dictLabel: label,
    });
    item_brand.value = rows.map((i) => {
      const { dictValue, dictLabel } = i;
      return {
        value: dictValue,
        label: dictLabel,
      };
    });
    brandLoading.value = false;
  }
}
/** 商品下拉框 */
const remoteLoading = ref(false);
const itemOptions = ref([]);
async function getItemOption(query) {
  if (query) {
    remoteLoading.value = true;
    const { data } = await optionSelect({ queryKey: query });
    itemOptions.value = data.map((i) => {
      const { id, brand, ref: re, recyclePrice, model, expressNo } = i;
      return {
        value: i.id,
        label: `${id},${brand},${re},${recyclePrice},${model},${
          expressNo || ""
        }`,
        recyclePrice: i.recyclePrice,
      };
    });
    remoteLoading.value = false;
  }
}
function handleChooseItem(id) {
  const { recyclePrice } = itemOptions.value.find((i) => i.value === id) || {
    recyclePrice: undefined,
  };
  addForm.value.recyclePrice = recyclePrice;
}

/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: i.userId,
        label: `${userId},${nickName},${userName}`,
        nickName,
        userName,
      };
    });
    userLoading.value = false;
  }
}
function handleChooseUser(userId) {
  const { label, userName, nickName } = userOptions.value.find(
    (i) => i.value === userId
  );
  addForm.value.recyclePerson = nickName;
  addForm.value.recyclePersonName = userName;
}
getItemOption(" ");
getUserOption(" ");
/** 获取商品详情 */
const fileList = ref([]);
const fileListBack = ref([]);
function getDetail() {
  loading.value = true;
  getRegister(props.params.id).then((response) => {
    const {
      recyclePersonId,
      paymentStatus,
      goodsStatus,
      watchImageUrl,
      watchImageUrlBack,
      brand,
    } = response.data[0];
    const rId =
      typeof recyclePersonId === "number"
        ? recyclePersonId + ""
        : recyclePersonId;
    const pS =
      typeof paymentStatus === "number" ? paymentStatus + "" : paymentStatus;
    const gS = typeof goodsStatus === "number" ? goodsStatus + "" : goodsStatus;
    addForm.value = {
      ...response.data[0],
      recyclePersonId: rId,
      paymentStatus: pS,
      goodsStatus: gS,
    };
    getItemBrand(brand);

    fileList.value[0] = { url: watchImageUrl };
    fileListBack.value[0] = { url: watchImageUrlBack };
    loading.value = false;
  });
}
/** 重置表单  */
function reset() {
  addForm.value.recyclePerson = undefined;
  addForm.value.recycleUsername = undefined;
  addForm.value.recyclePrice = undefined;
  proxy.resetForm("addRef");
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["addRef"].validate((valid) => {
    if (valid) {
      if (props.params.type === "add") {
        addRegister(addForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增回收登记成功");
          emits("refresh");
          cancel();
        });
      } else {
        updateRegister(addForm.value).then(
          (response) => {
            proxy.$modal.msgSuccess("修改回收登记成功");
            emits("refresh");
            cancel();
          }
        );
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  reset();
  emits("update:visible", false);
}
</script>
